package com.h2cloud.JUCTest.CyclicBarrier;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Package: com.h2cloud.JUCTest.CyclicBarrier
 * @ClassName: CyclicBarrierTest
 * @Author: h2cloud
 * @CreateTime: 2022/6/6 4:16 下午
 * @Description:
 */
@Slf4j
public class CyclicBarrierTest {
	public static void main(String[] args) throws InterruptedException {
		test1();
		// test2();
	}

	static void test2() {
		// 线程池数量 和 CyclicBarrier的数量 一样
		ExecutorService executorService = Executors.newFixedThreadPool(2);
		CyclicBarrier cyclicBarrier = new CyclicBarrier(2, () -> {
			log.info("task2 finish ...");
		});

		for (int i = 0; i < 3; i++) {
			final int time = i + 1;
			executorService.submit(() -> {
				log.info("task" + time + "-1 begin ...");
				try {
					Thread.sleep(1000);
					cyclicBarrier.await();
				} catch (InterruptedException | BrokenBarrierException e) {
					e.printStackTrace();
				}
			});
			executorService.submit(() -> {
				log.info("task" + time + "-2 begin ...");
				try {
					Thread.sleep(2000);
					cyclicBarrier.await();
				} catch (InterruptedException | BrokenBarrierException e) {
					e.printStackTrace();
				}
			});
		}

		executorService.shutdown();
	}

	static void test1() throws InterruptedException {
		CyclicBarrier cb = new CyclicBarrier(2); // 个数为2时才会继续执行
		for (int i = 0; i < 2; i++) {
			new Thread(() -> {
				log.debug("线程1开始..");
				try {
					cb.await(); // 当个数不足时，等待
				} catch (InterruptedException | BrokenBarrierException e) {
					e.printStackTrace();
				}
				log.debug("线程1继续向下运行...");
			}).start();


			new Thread(() -> {
				log.debug("线程2开始..");
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {

				}
				try {
					cb.await(); // 2 秒后，线程个数够2，继续运行
				} catch (InterruptedException | BrokenBarrierException e) {
					e.printStackTrace();
				}
				log.debug("线程2继续向下运行...");
			}).start();

			Thread.sleep(4000);
		}
	}
}


